package stdio.costa.moca.rest;

import java.io.IOException;
import java.io.InputStream;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.map.ObjectMapper;

import stdio.costa.moca.PostcardHandler;
import stdio.costa.moca.model.Address;
import stdio.costa.moca.model.Addresses;
import stdio.costa.moca.model.Img;
import stdio.costa.moca.model.Postcard;
import stdio.costa.moca.model.Postcards;
import stdio.costa.moca.pdf.AsposePdfPostcardHandler;
import stdio.costa.utils.IOUtils;

import com.sun.jersey.multipart.FormDataParam;

@Path("/postcard")
public class PostcardResource extends RestfulOperations {

	private PostcardHandler postcardPdfHandler = new AsposePdfPostcardHandler();
	
	@POST
	@Consumes(MediaType.MULTIPART_FORM_DATA)
	@Produces({ "application/json" })
	public Postcards createPostcard(
			@FormDataParam("front") InputStream front, 
			@FormDataParam("wish") InputStream wish,
			@FormDataParam("stamp") InputStream stamp, 
			@FormDataParam("userUuid") String userUuid,
			@FormDataParam("addresses") String addressesString) throws Exception {
		logger.info("Creating postcard...");
		loadUserByUuid(userUuid);
		Img frontImg = persist(front);
		Img wishImg = persist(wish);
		Img stampImg = persist(stamp);
		Postcards postcards = new Postcards();
		Addresses addresses = new ObjectMapper().readValue(addressesString, Addresses.class);
		for(Address address : addresses.getEntities()) {
			Postcard postcard = buildPostcard(frontImg, wishImg, stampImg, address);
			postcards.add(postcard);
			logger.info("Postcard created, uuid: {}", postcard.getUuid());
			if(postcard.isReadyForPdfGeneration()) {
				logger.info("Converting postcard {} to pdf.", postcard.getUuid());
				postcard = postcardPdfHandler.handle(postcard);
				logger.debug("Postcard pdf has been generated: {}", postcard.isPdfGenerated());
			} else {
				// send notification, mail, message, weibo message, etc. FIXME
			}
		}
		logger.info("{} postcards has been created.", postcards.size());
		return postcards;
	}

	private Postcard buildPostcard(Img frontImg, Img wishImg, Img stampImg, Address address) {
		Postcard postcard = new Postcard();
		postcard.setPhoto(frontImg);
		postcard.setWish(wishImg);
		postcard.setStamp(stampImg);
		postcard.setAddress(address);
		postcard.setSender(getCurrentUser());
		getEntityManager().persist(postcard);
		return postcard;
	}

	private Img persist(InputStream inputStream) throws IOException {
		logger.info("Reading image data from request...");
		byte[] original = IOUtils.read(inputStream);
		logger.info("Image data has been read, original size is {} bytes.", original.length);
		Img img = new Img(original);
		getEntityManager().persist(img);
		return img;
	}
}
